package com.laohei.bili_tube

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import com.laohei.bili_sdk.wbi.GetWbi
import com.laohei.bili_sdk.wbi.WbiParams
import com.laohei.bili_tube.core.COOKIE_KEY
import com.laohei.bili_tube.core.IMG_URL_KEY
import com.laohei.bili_tube.core.SUB_URL_KEY
import com.laohei.bili_tube.core.util.SystemUtil
import com.laohei.bili_tube.di.appModule
import com.laohei.bili_tube.utill.HttpClientFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin

//创建一个名为 bili_tube 的 DataStore<Preferences> 实例
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "bili_tube")

class BiliTubeApp : Application() {
    companion object {
        private val TAG = BiliTubeApp::class.simpleName
    }

    //在应用程序初始化的时候做一些事情
    override fun onCreate() {
        super.onCreate()
        //这个里面初始化一些尺寸信息
        SystemUtil.init(this)
        //初始化koin
        startKoin {
            androidContext(this@BiliTubeApp)
            modules(appModule)
        }
        CoroutineScope(Dispatchers.IO).launch {
            //初始化bilibili的wbi签名
            if (WbiParams.wbi == null) {
                //dataStore.data 用来读取数据
                val imgKey = dataStore.data.firstOrNull()?.get(IMG_URL_KEY)
                val subKey = dataStore.data.firstOrNull()?.get(SUB_URL_KEY)
                if (imgKey != null && subKey != null) {
                    WbiParams.initWbi(imgKey, subKey)
                    Log.d(TAG, "onCreate: $imgKey $subKey")
                } else {
                    val cookie = dataStore.data.firstOrNull()?.get(COOKIE_KEY)
                    GetWbi.getWbiRequest(HttpClientFactory.client)
                        .wbi(cookie) { biliWbi ->
                            //dataStore.edit 用来写入数据
                            dataStore.edit { settings ->
                                settings[IMG_URL_KEY] = biliWbi.wbiImg.imgUrl
                                settings[SUB_URL_KEY] = biliWbi.wbiImg.subUrl
                            }
                        }
                }
            }
        }
    }
}